/**
 * 
 */
package com.hk.Mgr.web.controller.common;

import com.hk.Mgr.web.message.kyc.AgreementRes;
import com.hk.Mgr.web.message.sys.SysUserReq;
import com.hk.base.BaseCtrl;
import com.hk.base.ResponseBase;
import com.hk.commons.HqlFilter;
import com.hk.commons.ReqToModelHelper;
import com.hk.commons.ResultCode;
import com.hk.commons.entity.Agreement;
import com.hk.commons.entity.product.Payment;
import com.hk.commons.entity.product.ProductInfo;
import com.hk.commons.entity.sys.SysUser;
import com.hk.service.kyc.IAgreement;
import com.hk.service.order.IPayment;
import com.hk.service.product.IProductInfo;
import com.hk.service.sys.ISysUser;
import org.apache.commons.lang.StringUtils;
import org.hibernate.annotations.common.util.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author psx 产品信息实现类
 */
@Controller
@RequestMapping(value = BaseCtrl.CommonRootPath + "/agreementCtrl")
public class ComAgreementCtrl {

	private Logger logger = LoggerFactory.getLogger(ComAgreementCtrl.class);

	@Autowired
	private IAgreement agreementService;
	
	@Autowired
	private ISysUser sysUserService;

	@Autowired
	private IProductInfo productService;

	@Autowired
	private IPayment paymentService;

	/**
	 * 手机专用
	 * 
	 * @Title: getProductInfoList
	 * @Description: 分页获取系统模块
	 * @param
	 */
	@ResponseBody
	@RequestMapping(value = "/getById", method = RequestMethod.GET)
	public ResponseBase<String> getInfoById(String strId, Long userId, String amt,Long productId) {

		logger.info("获取协议 strId={}， userId={}, amt={}, productId={}",strId, userId, amt,productId);

		ResponseBase<String> rb = new ResponseBase<>();

		if(StringHelper.isEmpty(strId)){
			rb.setResult("参数错误");
			rb.setResultCode(ResultCode.PARAM_ERROR.getCode());
			return rb;
		}

		Long id = Long.valueOf(strId);

		String msg = agreementService.getByInfo(id, userId, amt);
		msg = replaceProductInfo(msg,productId, userId);
		rb.setResult(msg);
		rb.setResultCode(ResultCode.SUCC.getCode());

		return rb;
	}
	
	@RequestMapping(value = "/getUrl", method = RequestMethod.GET)
	@ResponseBody
	public ResponseBase<AgreementRes>  getUrl() {
		AgreementRes agreement = new AgreementRes();
		ResponseBase resp = new ResponseBase();
		String Url = "mobile/agreement/agreementShow.html";
		agreement.setUrl(Url);
		resp.setResult(agreement);
		return resp;
	}
	
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	public ResponseBase<List<AgreementRes>> list(
			@RequestBody SysUserReq req) {
		ResponseBase<List<AgreementRes>> resp = new ResponseBase<>();
		List<AgreementRes> orderReslist = new ArrayList<>();

		HqlFilter hqlFilter = new HqlFilter();

		if (StringUtils.isNotEmpty(req.getName())) {
			hqlFilter.addLKFilter("name", req.getName());
		}

		hqlFilter.addSort("cts");
		hqlFilter.addOrder("desc");

		List<Agreement> list = agreementService.findByFilter(hqlFilter,
				req.getCurPage(), req.getPageSize());

		for (Agreement ag : list) {
			AgreementRes agreementRes = new AgreementRes();

			ReqToModelHelper.copyReqValueToModel(ag, agreementRes);
			
			
			// 增添创建者姓名
			SysUser creater = new SysUser();
			if (ag.getCreater() != null
					&& sysUserService.existById(ag.getCreater())) {
				creater = sysUserService.findById(ag.getCreater());
				agreementRes.setCreaterName(creater.getRealName());
			}

			if (ag.getAgreement() != null) {
				String agreement;
				try {
					agreement = new String(ag.getAgreement(), "UTF-8");
					agreementRes.setAgreementText(agreement);

				} catch (UnsupportedEncodingException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					logger.error("agreementCtl/update 类型转换错误" + "id = "
							+ req.getId());
				}

				orderReslist.add(agreementRes);
			}
			resp.setResult(orderReslist);
			resp.setSize(orderReslist.size());
			resp.setResult(orderReslist);
		}

		return resp;
	}

	/**
	 * 协议里面添加产品相关信息
	 * @param content
	 * @param productId
	 * @return
	 */
	private String  replaceProductInfo(String content,Long productId, Long userId){
		if(productId == null || StringUtils.isBlank(content)){
			return content;
		}

		ProductInfo productInfo = productService.findById(productId);
		if(productId == null){
			return content;
		}

		String agreementProductName = productInfo.getAgreementProductName();
		if(StringUtils.isBlank(agreementProductName)){
			agreementProductName = productInfo.getName();
		}

		String result = content.replace("agreementProductName",agreementProductName);
		result = result.replace("proTerm",productInfo.getProTermStr());
		result = result.replace("maxYearRate",productInfo.getMaxYearRate());
		//挂牌号
		if(StringUtils.isNotBlank(productInfo.getListingNumber())){
			result = result.replace("listingNumber",productInfo.getListingNumber());
		}

		//备案号
		if(!StringUtils.isBlank(productInfo.getLicenseNumber())) {
			result = result.replace("licenseNumber", productInfo.getLicenseNumber());
		}

		//银行卡号
		Payment payment = paymentService.getByUserId(userId);
		if(!StringUtils.isBlank(payment.getPaymentNo())) {
			result = result.replace("paymentNo", payment.getPaymentNo());
		}

		//银行名称
		if(!StringUtils.isBlank(payment.getBankName())) {
			result = result.replace("bankName", payment.getBankName());
		}


		return result;
	}

}
